import * as vscode from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import { DisplayNameManager } from './displayNameManage';
import { FileItem } from './types';

class AutoOfficeTreeItem implements FileItem {
    constructor(
        public readonly label: string,
        public readonly collapsibleState: vscode.TreeItemCollapsibleState,
        public readonly filePath: string,
        public readonly actualFilename: string
    ) {
        this.tooltip = label;
        this.description = '';
    }

    tooltip?: string;
    description: string;
    iconPath?: string | vscode.Uri | { light: string | vscode.Uri; dark: string | vscode.Uri } | vscode.ThemeIcon;
    command?: vscode.Command;
    contextValue?: string;
}

class AutoOfficeTreeDataProvider implements vscode.TreeDataProvider<FileItem> {
    private _onDidChangeTreeData: vscode.EventEmitter<FileItem | undefined | null | void> = new vscode.EventEmitter<FileItem | undefined | null | void>();
    readonly onDidChangeTreeData: vscode.Event<FileItem | undefined | null | void> = this._onDidChangeTreeData.event;

    constructor(
        private workspaceRoot: string,
        private extensionPath: string,
        private displayNameManager: DisplayNameManager
    ) {}

    refresh(): void {
        this._onDidChangeTreeData.fire();
    }

    getTreeItem(element: FileItem): vscode.TreeItem {
        return element;
    }

    async getChildren(element?: FileItem): Promise<FileItem[]> {
        if (!element) {
            const projectPath = path.join(
                this.extensionPath,
                'resources',
                'files',
                'auto-office'
            );
            return this.getFilesInDirectory(projectPath);
        } else {
            return this.getFilesInDirectory(element.filePath);
        }
    }

    private async getFilesInDirectory(dir: string): Promise<FileItem[]> {
        const items: FileItem[] = [];

        if (fs.existsSync(dir)) {
            const files = fs.readdirSync(dir);

            files.sort((a, b) => {
                const aPath = path.join(dir, a);
                const bPath = path.join(dir, b);
                const aIsDir = fs.statSync(aPath).isDirectory();
                const bIsDir = fs.statSync(bPath).isDirectory();

                if (aIsDir && !bIsDir) return -1;
                if (!aIsDir && bIsDir) return 1;
                return a.localeCompare(b);
            });

            for (const file of files) {
                if (file === 'display_names.json') continue;
                
                const filePath = path.join(dir, file);
                const stat = fs.statSync(filePath);
                const displayName = this.displayNameManager.getDisplayName(file);

                if (stat.isDirectory()) {
                    const item = new AutoOfficeTreeItem(
                        displayName,
                        vscode.TreeItemCollapsibleState.Collapsed,
                        filePath,
                        file
                    );
                    item.iconPath = new vscode.ThemeIcon("folder");
                    items.push(item);
                } else {
                    const item = new AutoOfficeTreeItem(
                        displayName,
                        vscode.TreeItemCollapsibleState.None,
                        filePath,
                        file
                    );
                    item.command = {
                        command: "auto-office.openFile",
                        title: "Open File",
                        arguments: [filePath],
                    };
                    item.iconPath = new vscode.ThemeIcon("file");
                    items.push(item);
                }
            }
        }

        return items;
    }
}

export async function activate(context: vscode.ExtensionContext) {
    console.log('Extension "vscode-auto-office" is now active!');

    // 初始化显示名称管理器
    const displayNameManager = new DisplayNameManager(context.extensionPath);
    
    // 恢复显示名称
    await displayNameManager.restoreDisplayNames();
    
    // 创建树视图提供者
    const treeDataProvider = new AutoOfficeTreeDataProvider(
        vscode.workspace.rootPath || "",
        context.extensionPath,
        displayNameManager
    );
    
    // 注册树视图
    vscode.window.registerTreeDataProvider(
        "auto-office-view",
        treeDataProvider
    );

    // 注册打开文件命令
    let openFileCommand = vscode.commands.registerCommand(
        "auto-office.openFile",
        (filePath: string) => {
            vscode.workspace.openTextDocument(filePath).then((doc) => {
                vscode.window.showTextDocument(doc);
            });
        }
    );

    // 注册停用事件处理
    context.subscriptions.push(
        new vscode.Disposable(() => {
            displayNameManager.restoreSafeNames();
        })
    );

    // 添加到订阅列表
    context.subscriptions.push(openFileCommand);
}

export function deactivate() {}